package com.training.service;

import com.training.entity.Student; // Import Student entity
import com.training.entity.User; // Import User entity
import com.training.entity.Class; // Import Class entity
import com.training.entity.Course; // Import Course entity (NEW)
import com.training.mapper.StudentMapper; // Import StudentMapper
import com.training.mapper.ClassStudentMapper; // Import ClassStudentMapper
import com.training.mapper.CouClassMapper; // Import CouClassMapper (NEW)
// import com.training.mapper.PurchaseRecordMapper; // NEW: Import PurchaseRecordMapper if you have one
import org.springframework.beans.factory.annotation.Autowired; // Import Autowired annotation
import org.springframework.stereotype.Service; // Import Service annotation
import org.springframework.transaction.annotation.Transactional; // Import Transactional annotation

import java.util.List; // Import List collection
import java.util.ArrayList; // Import ArrayList (potentially needed for mapping)

@Service // Mark this as a Service class, Spring will manage it
public class StudentService {

    @Autowired // Auto-inject StudentMapper instance
    private StudentMapper studentMapper;

    @Autowired // Auto-inject UserService instance
    private UserService userService; // 确保 UserService 已注入

    @Autowired // Auto-inject ClassStudentMapper instance
    private ClassStudentMapper classStudentMapper; // Inject ClassStudentMapper

    @Autowired // Auto-inject CouClassMapper instance (NEW)
    private CouClassMapper couClassMapper;

    // // NEW: If you have a PurchaseRecordMapper to check purchased courses, uncomment and inject it
    // @Autowired
    // private PurchaseRecordMapper purchaseRecordMapper;


    /**
     * Find student record by user ID
     * @param userId User ID (from user table)
     * @return Corresponding Student object, null if not found
     */
    public Student getStudentByUserId(Long userId) {
        return studentMapper.findByUserId(userId);
    }

    /**
     * Get student ID by user ID.
     * @param userId User ID
     * @return Student ID, or null if not found
     */
    public Long getStudentIdByUserId(Long userId) {
        Student student = studentMapper.findByUserId(userId);
        return student != null ? student.getId() : null;
    }

    /**
     * Find student record by student ID
     * @param id Student ID
     * @return Corresponding Student object, null if not found
     */
    public Student getStudentById(Long id) {
        return studentMapper.findById(id); // Corrected method call to findById
    }


    /**
     * NEW: Find student record by student number (stuNum).
     * @param stuNum Student number
     * @return Corresponding Student object, null if not found
     */
    public Student getStudentByStuNum(String stuNum) {
        return studentMapper.findByStuNum(stuNum);
    }

    /**
     * Get list of all non-logically deleted students.
     * @return List of Student objects
     */
    public List<Student> findAllStudents() {
        return studentMapper.findAllStudents();
    }

    @Transactional
    public boolean updateStudent(Student student){
        return studentMapper.updateStudent(student) > 0;
    }
    /**
     * Fuzzy search for non-logically deleted students by student name.
     * @param stuName Student name (fuzzy search keyword)
     * @return List of Student objects
     */
    public List<Student> searchStudentsByName(String stuName) {
        return studentMapper.findStudentsByName(stuName);
    }

    /**
     * Add a new student record, including creating a new user account.
     *
     * @param student The Student object to insert (stuName, stuNum)
     * @param username The username for the new user account
     * @param password The password for the new user account
     * @return true if added successfully, false otherwise (e.g., stuNum or username already exists)
     */
    @Transactional // 事务管理，确保用户和学生数据一致性
    public boolean addStudent(Student student, String username, String password) {
        // 1. 检查学号是否已存在
        if (studentMapper.findByStuNum(student.getStuNum()) != null) {
            System.err.println("学生学号已存在: " + student.getStuNum());
            return false; // 学号已存在
        }

        // 2. 检查用户名是否已存在
        if (userService.findByUsername(username) != null) { // 假设 UserService 有 findByUsername 方法
            System.err.println("用户名已存在: " + username);
            return false; // 用户名已存在
        }

        // 3. 创建新用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 密码应在 UserService 中进行加密
        newUser.setRole("STUDENT"); // 设置用户角色为学生

        try {
            User createdUser = userService.saveUser(newUser);
            if (createdUser == null || createdUser.getId() == null) {
                System.err.println("用户注册失败，用户名可能已存在或未知错误。");
                return false;
            }
            student.setUserId(createdUser.getId());

            // 4. 插入学生信息 (这里保持积分初始化为1000的修改)
            student.setDeleted(0); // 默认未删除
            student.setStuStudyTime(0L); // 默认学习时间
            student.setStuScore(1000L); // 将默认积分设置为 1000
            student.setClock("0000000"); // 默认打卡次数
            int affectedRows = studentMapper.insertStudent(student);

            return affectedRows > 0;
        } catch (Exception e) {
            System.err.println("添加学生过程中发生错误: " + e.getMessage());
            return false;
        }
    }

    /**
     * Update an existing student record, including updating user account information.
     *
     * @param student The Student object to update (id, stuName, stuNum)
     * @param username The new username (if changed)
     * @param password The new password (if changed, can be empty if not changing)
     * @return true if updated successfully, false otherwise
     */
    @Transactional // 事务管理
    public boolean saveStudent(Student student, String username, String password) {
        // 1. 检查学号是否被其他学生占用（如果学号有修改）
        Student existingStudentByNum = studentMapper.findByStuNum(student.getStuNum());
        if (existingStudentByNum != null && !existingStudentByNum.getId().equals(student.getId())) {
            System.err.println("更新学生信息失败：学号已被其他学生占用。");
            return false;
        }

        // 2. 更新关联的用户信息
        User associatedUser = userService.getUserById(student.getUserId());
        if (associatedUser == null) {
            System.err.println("更新学生信息失败：未找到关联的用户。");
            return false; // 找不到关联用户
        }

        // 检查用户名是否被其他用户占用（如果用户名有修改）
        User existingUserByUsername = userService.findByUsername(username); // 假设 UserService 有 findByUsername 方法
        if (existingUserByUsername != null && !existingUserByUsername.getId().equals(associatedUser.getId())) {
            System.err.println("更新学生信息失败：用户名已被其他用户占用。");
            return false;
        }

        associatedUser.setUsername(username);
        if (password != null && !password.isEmpty()) {
            associatedUser.setPassword(password); // 密码应在 UserService 中进行加密
        }
        try {
            boolean userUpdateSuccess = userService.updateUser(associatedUser); // 假设此方法处理了密码加密和重复用户名检查
            if (!userUpdateSuccess) {
                System.err.println("更新学生关联的用户信息失败。");
                return false;
            }
        } catch (Exception e) {
            System.err.println("更新学生关联的用户信息过程中发生错误: " + e.getMessage());
            return false;
        }

        // 3. 更新学生信息
        int affectedRows = studentMapper.updateStudent(student);
        return affectedRows > 0;
    }

    /**
     * Logically delete a student record and its associated user account.
     * @param id Student ID to delete
     * @return true if deleted successfully, false otherwise
     */
    @Transactional // 事务管理
    public boolean deleteStudent(Long id) {
        Student studentToDelete = studentMapper.findById(id);
        if (studentToDelete == null) {
            return false; // 学生不存在
        }

        // 1. 逻辑删除学生记录
        int studentAffectedRows = studentMapper.deleteStudent(id);

        // 2. 逻辑删除关联的用户记录
        boolean userDeleteSuccess = true; // 将 int 类型改为 boolean 类型
        if (studentToDelete.getUserId() != null) {
            userDeleteSuccess = userService.deleteUser(studentToDelete.getUserId()); // 这里现在是 boolean 赋值给 boolean，类型兼容
        }

        // 只有当学生删除成功且关联的用户删除成功 (如果存在用户) 时才返回 true
        return studentAffectedRows > 0 && userDeleteSuccess;
    }

    /**
     * Get all non-logically deleted classes a student is enrolled in.
     * Corresponds to requirement FR-BJ-1.
     * @param studentId Student ID
     * @return List of Class objects that the student is part of
     */
    public List<Class> getEnrolledClasses(Long studentId) {
        return classStudentMapper.findClassesByStudentId(studentId);
    }

    /**
     * NEW: Get all non-logically deleted courses associated with a specific class.
     * Corresponds to requirement FR-BJ-2.
     * @param classId Class ID
     * @return List of Course objects associated with the class
     */
    public List<Course> getCoursesByClassId(Long classId) {
        return couClassMapper.findCoursesByClassId(classId);
    }

    /**
     * NEW: Check if a student has purchased a specific course.
     * This method will require interaction with your PurchaseRecord/ShoppingCart data.
     * You'll need to implement the actual logic, likely by querying a purchase record table
     * or a shopping cart table that indicates purchased courses.
     * @param studentId Student ID
     * @param courseId Course ID
     * @return true if the student has purchased the course, false otherwise
     */
    public boolean hasStudentPurchasedCourse(Long studentId, Long courseId) {
        // TODO: Implement the actual logic to check if the student has purchased the course.
        // This will likely involve querying a purchase record or order table
        // that links student IDs to course IDs.
        // Example (conceptual, you need to adapt to your actual data model and mappers):
        // If you have a PurchaseRecordMapper and a method like findByStudentIdAndCourseId:
        // return purchaseRecordMapper.findByStudentIdAndCourseId(studentId, courseId) != null;

        // For now, returning false as a placeholder to resolve the compilation error.
        return false;
    }
}